package com.cxx.purchasecharge.component.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.GoodsDepositoryBean;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.BeanConvertUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.GoodsDepository;
import com.cxx.purchasecharge.dal.GoodsDepositoryDao;

@Controller
@RequestMapping (GoodsDepositoryManager.CONTROLLER_GOODS_DEPOSITORY)
public class GoodsDepositoryManager extends GenericController <GoodsDepositoryBean>
{
    private static final Logger logger = Logger.getLogger (GoodsDepositoryManager.class);

    @Autowired
    private GoodsDepositoryDao goodsDepositoryDao;
    
    public final static String CONTROLLER_GOODS_DEPOSITORY = "/goodsDepository";

    public GoodsDepositoryManager()
    {
        super.setViewName("goodsDepositoryMgmt");
    }

    public @ResponseBody
    String checkExist (@RequestParam String goodsDepositoryId, @RequestParam String name, HttpServletRequest request)
    {
        if (StringUtils.isBlank (goodsDepositoryId))
        {
            // new
            GoodsDepository obj = goodsDepositoryDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long id = Long.parseLong (goodsDepositoryId);
            GoodsDepository goodsDepository = goodsDepositoryDao.findByName (name);
            if (null != goodsDepository && goodsDepository.getId () != id)
            {
                return "false";
            }
        }

        return "true";
    }

    public @ResponseBody
    String getAllModel (DataGridRequestForm dataGridRequestForm, HttpServletRequest request)
    {
        List <GoodsDepository> goodsDepositorys = (List <GoodsDepository>) goodsDepositoryDao.findAll ();
        List <GoodsDepositoryBean> goodsDepositoryBeans = new ArrayList <GoodsDepositoryBean> ();
        if (null != goodsDepositorys)
        {
            for (GoodsDepository goodsDepository : goodsDepositorys)
            {
                goodsDepositoryBeans.add(BeanConvertUtils.goodsDepository2GoodsDepositoryBean(goodsDepository));
            }
        }
        JSONArray jsonObject = JSONArray.fromObject (goodsDepositoryBeans);
        return jsonObject.toString ();
    }
    
    public @ResponseBody
    String addModel (GoodsDepositoryBean goodsDepositoryBean, BindingResult bindingResult, HttpServletRequest request)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            GoodsDepository goodsDepository = BeanConvertUtils.goodsDepositoryBean2GoodsDepository (goodsDepositoryBean);

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                goodsDepositoryDao.save (goodsDepository);
                ar = ActionResult.ok ()
                    .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                          ComponentConstants.MSG_GOODS_DEPOSITORY))
                    .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                              .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                                    ComponentConstants.MSG_GOODS_DEPOSITORY))
                                              .build ();
            }
            
            return AjaxUtils.getJsonObject (ar);
        }
    }

    public @ResponseBody
    String updateModel (GoodsDepositoryBean goodsDepositoryBean, BindingResult bindingResult, HttpServletRequest request)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject(ar);
        }
        else
        {
            GoodsDepository goodsDepository = BeanConvertUtils.goodsDepositoryBean2GoodsDepository (goodsDepositoryBean);
            
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                goodsDepositoryDao.save (goodsDepository);
                ar = ActionResult.ok ()
                    .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                          ComponentConstants.MSG_GOODS_DEPOSITORY))
                    .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                              .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                                    ComponentConstants.MSG_GOODS_DEPOSITORY))
                                              .build ();
            }
            
            return AjaxUtils.getJsonObject(ar);
        }
    }

    public @ResponseBody
    String deleteModels (@RequestParam String ids, HttpServletRequest request)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                List <GoodsDepository> depositories = new ArrayList <GoodsDepository> ();
                GoodsDepository depository;
                for (String typeId : idArr)
                {
                    depository = new GoodsDepository ();
                    depository.setId (Long.parseLong (typeId));
                    depositories.add (depository);
                }

                try
                {
                    goodsDepositoryDao.delete (depositories);
                    ar = ActionResult.ok ()
                                     .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                           ComponentConstants.MSG_GOODS_DEPOSITORY))
                                     .build ();
                }
                catch (Exception e)
                {
                    logger.error (e.getMessage (), e);
                    ar = ActionResult.serverError ()
                                     .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                           ComponentConstants.MSG_GOODS_DEPOSITORY))
                                     .build ();
                }
            }
            else
            {
                try
                {
                    goodsDepositoryDao.delete (Long.parseLong (ids));
                    ar = ActionResult.ok ()
                                     .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                           ComponentConstants.MSG_GOODS_DEPOSITORY))
                                     .build ();
                }
                catch (Exception e)
                {
                    logger.error (e.getMessage (), e);
                    ar = ActionResult.serverError ()
                                     .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                           ComponentConstants.MSG_GOODS_DEPOSITORY))
                                     .build ();
                }
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }

}
